<?php

function updateTotalFriends($iValue)
{
	isUser();	
	$oRespX = new xajaxResponse();		
	$oDb =& Database::get();
	$oDb->update(App::getT('user'), array('total_friends' => $iValue), "id = '" . App::getUser('id') . "'");	
	$oRespX->addAssign('totalFriendsSaved', 'innerHTML', App::format('Mod_Account.saved'));
	$oRespX->addScript('setTimeout("sId(\'totalFriendsSaved\').innerHTML=\'\'", 3000);');
	
	$sParams = array
	(
		'add' => '',
		'remove' => false,
		'iForceDisplay' => $iValue
	);	
	
	$oSrvVideo = &App::getModuleComponent('Account', 'AjaxTopFriends', $sParams);
	$sGetProcess = $oSrvVideo->process();
	$oRespX->addAssign("top_friends","innerHTML", $sGetProcess);
	
	return $oRespX;	
}

function randomCaptcha($iId, $iInput)
{
	$oRespX = new xajaxResponse();		
	
	$oRespX->addScript("sId('" . $iId . "').src='" . App::makeUrl('public.randimage', array('r' => md5(rand(100, 1000)))) . "';");
	$oRespX->addScript("sId('" . $iInput . "').focus();");
	
	return $oRespX;
}

function updateFriendsCount($aParams)
{
	$oRespX = new xajaxResponse();	
	$oDb =& Database::get();

	$aTemp = split("&", $aParams);
	$aUser = array();
	foreach ($aTemp as $iKey => $sTemp) 
	{
		$iKey++;
		$aUser[$iKey] = trim(str_replace('list[]=', '', str_replace('%7C', '_', $sTemp)));
		$oDb->update(App::getT('friends'), array('top_order' => $iKey), "user = '" . App::getUser('user') . "' AND friend = '" . $aUser[$iKey] . "'");
	}

	return $oRespX;
}

function displayTopFriends($sUser = "", $iRemove = false)
{
	isUser();

	$oRespX = new xajaxResponse();
	
	$sParams = array
	(
		'add' => $sUser,
		'remove' => $iRemove,
	);

	$oSrvVideo = &App::getModuleComponent('Account', 'AjaxTopFriends', $sParams);
	$sGetProcess = $oSrvVideo->process();

	if ( $sGetProcess == 'is_already_top' )
	{
		$oRespX->addScript("alert('". App::format('Mod_Account.already_top_user') ."');");
	}
	elseif ( $sGetProcess == 'reached_limit' )
	{
		$oRespX->addScript("alert('". App::format('Mod_Account.reached_top_limit') ."');");
	}
	else
	{
		$oRespX->addAssign("top_friends","innerHTML", $sGetProcess);
		if (!$iRemove)
		{
			$oRespX->addAssign("users_added", "innerHTML", "Added " . $sUser . "!");
			$oRespX->addScript("setTimeout('sId(\'users_added\').innerHTML=\'\';', 5000);");
		}
		$oRespX->addScript('Sortable.create("list", {constraint:\'horizontal\', onUpdate:function(){xajax_updateFriendsCount(Sortable.serialize("list"));}})');
	}

	return $oRespX;
}

function changeImStatus($iStatus)
{
	$oRespX = new xajaxResponse();
	chatMembersOnly($oRespX);
	$oDb =& Database::get();
	$oDb->update(App::getT('user'), array('im_status' => $iStatus), "user = '". App::getUser('user') ."'");
	return $oRespX;
}

function searchMyFriends($sName, $sDiv, $sCommand, $sLimit = 10)
{
	isUser();
	$oRespX = new xajaxResponse();
	$sName = trim($sName);
	if ( empty($sName) )
	{
		$oRespX->addScript("document.getElementById('". $sDiv ."').style.display='none';");
		return $oRespX;
	}

	$oDb =& Database::get();
	$aRows = $oDb->getRows("
		SELECT f.friend AS user, u.id FROM
			". App::getT('friends') ." AS f
				JOIN ". App::getT('user') ." AS u ON (f.friend = u.user)
		WHERE f.friend LIKE '%". $oDb->escape($sName) ."%' AND f.user = '". App::getUser('user') ."' LIMIT ". $sLimit."
	");

	if ( !count($aRows) )
	{
		$oRespX->addScript("document.getElementById('". $sDiv ."').style.display='none';");
		return $oRespX;
	}
	$sTemplate = '';
	$iCnt = 0;
	foreach( $aRows as $aRow )
	{
		$iCnt++;
		$sTemplate .= '<div style="padding:2px;"'. (is_int($iCnt/2) ? ' class="border13"' : '') .'><a href="javascript:void(0);" onclick="'. sprintf($sCommand, $aRow['user']) .' sId(\''. $sDiv .'\').style.display=\'none\';">'. $aRow['user'] .'</a></div>';
	}
	$oRespX->addScript("document.getElementById('". $sDiv ."').style.display='';");
	$oRespX->addAssign($sDiv,"innerHTML", $sTemplate);
	return $oRespX;
}

function searchFriends($sName, $sDiv)
{
	$oRespX = new xajaxResponse();
	chatMembersOnly($oRespX);
	$sName = trim($sName);
	if ( empty($sName) )
	{
		$oRespX->addScript("document.getElementById('". $sDiv ."').style.display='none';");
		return $oRespX;
	}

	$iTimeout = time() - App::getSetting('max_time_online') * 60;

	$oDb =& Database::get();
	$aRows = $oDb->getRows("
		SELECT f.friend AS user, u.id FROM
			". App::getT('friends') ." AS f
				JOIN ". App::getT('user') ." AS u ON (f.friend = u.user)
				JOIN ". App::getT('msg_online') ." AS m ON (m.userid = u.id  AND m.time > '". $iTimeout ."')
		WHERE f.friend LIKE '%". $oDb->escape($sName) ."%' AND f.user = '". App::getUser('user') ."' LIMIT 10
	");
	if ( !count($aRows) )
	{
		$oRespX->addScript("document.getElementById('". $sDiv ."').style.display='none';");
		return $oRespX;
	}
	$sTemplate = '';
	$iCnt = 0;
	$iImChatWidth = App::getParam('im_chat_width');
    $iImChatHeight = App::getParam('im_chat_height');
	foreach( $aRows as $aRow )
	{
		$iCnt++;
		$sTemplate .= '<div style="padding:2px;"'. (is_int($iCnt/2) ? ' class="border13"' : '') .'><a style="cursor:pointer;" href="javascript:void(0);" onclick="popUp2(\''. App::makeUrl('public.account.messenger.chat', array('userid' => $aRow['id'], 'type' => 'request')) .'\',\''. $iImChatHeight .'\',\''. $iImChatWidth .'\',\'yes\',\'200\',\'100\');">'. $aRow['user'] .'</a></div>';
	}
	$oRespX->addScript("document.getElementById('". $sDiv ."').style.display='';");
	$oRespX->addAssign($sDiv,"innerHTML", $sTemplate);
	return $oRespX;
}

function addMessage($iRoomId, $sText, $sUser)
{
	$oRespX = new xajaxResponse();
	chatMembersOnly($oRespX);
	$oDb =& Database::get();

	define('PHPFOX_PROTECT_IMG', true);

	App::loadClass('Text');
    $oTxt = new Text();

    $sText = $oTxt->preParseChat($sText);

	if ( empty($sText) )
	{
		return $oRespX;
	}

    $sText = $oTxt->parsePostChat($sText);
    $sText = $oTxt->utf8ToUnicode($sText);
    $sData = '<div style="padding-left:4px; margin-bottom:8px;"><a href="'. App::makeUrl('public.user', array('name' => App::getUser('user'))) .'" target="_blank">'. App::getUser('user') .'</a> '. App::format('Mod_Chat.wrote') .':<div style="padding-top:1px; padding-left:8px;">'. $sText .'</div></div>';
    $oRespX->addScript("document.getElementById('chat_content').innerHTML = document.getElementById('chat_content').innerHTML + '". str_replace("'", "\'", $sData) ."'; document.getElementById('chat_content_div').scrollTop = document.getElementById('chat_content_div').scrollHeight;");
	$oDb->insert(App::getT('msg_chat'), array('requestid' => $iRoomId, 'userid' => App::getUser('id'), 'text' => $sText, 'time' => time()));
	// $oDb->insert(App::getT('msg_chat'), array('requestid' => $iRoomId, 'text' => '[BGSOUND]' . $sUser . '[/BGSOUND]', 'time' => time()));
	// $oRespX->addAssign("chat_content","innerHTML", getMessages($iRoomId, true));
	return $oRespX;
}

function deleteSessions()
{
	if (!App::getUser('user'))
	{
		return;
	}
	$oDb =& Database::get();	
	$oDb->_delete(App::getT('msg_room'), "userid = '". App::getUser('id') ."'");
	$oDb->_delete(App::getT('msg_request'), "userid = '". App::getUser('id') ."'");
	$oDb->update(App::getT('msg_online'), array('time' => 0), "userid = '". App::getUser('id') ."'");	
}

function deleteFromRoom($iId)
{
	if (!App::getUser('user'))
	{
		return;
	}
	$oDb =& Database::get();	
	$oDb->_delete(App::getT('msg_room'), "requestid = '". $iId ."' AND userid = '". App::getUser('id') ."'");
	$oDb->_delete(App::getT('msg_request'), "requestid = '". $iId ."'");
}

function getImStatus($iUserId, $iRoomId, $sOldStatus = '')
{
	$oRespX = new xajaxResponse();
	$oDb =& Database::get();
	$aRow = $oDb->getRow("
		SELECT u.user, o.text, r.requestid, m.requestid AS is_online FROM
			". App::getT('user') ." AS u
			LEFT JOIN ". App::getT('language_options') ." AS o ON(o.varid = u.im_status AND o.varname = 'im_status' AND o.languageid = '". App::langParam('id') ."')
			LEFT JOIN ". App::getT('msg_room') ." AS r ON(r.requestid = '". $iRoomId ."' AND r.userid = '". $iUserId ."')
			LEFT JOIN ". App::getT('msg_room') ." AS m ON(m.requestid = '". $iRoomId ."' AND m.userid = '". App::getUser('id') ."')
		WHERE id = '". $iUserId ."'
	");
	
	if (!$aRow['requestid'] && $aRow['is_online']) 
	{
		$oRespX->addAssign('system_message', 'innerHTML', '<b>'. App::format('Mod_Messenger.user_left_the_room', $aRow['user']) .'</b>');
	}
	if (!$aRow['is_online']) 
	{
		$oRespX->addAssign('system_message', 'innerHTML', '<b>'. App::format('Mod_Messenger.not_available', $aRow['user']) .'</b>');
		// $oRespX->addScript('window.focus();setTimeout("window.close();", 9000);');
	}
	
	$oRespX->addAssign("user_data", "innerHTML", ''. $aRow['user'] .' '. ($aRow['text'] ? '('. $aRow['text'] .')' : '') .'');
	$oRespX->addScript('setTimeout("xajax_getImStatus(\''. $iUserId .'\', \''. $iRoomId .'\', \''. $aRow['text'] .'\')", 60000);');
	return $oRespX;
}

function saveUserSetting($iSetting)
{
	$oRespX = new xajaxResponse();
	$oDb =& Database::get();
	$oDb->update(App::getT('user'), array('msg_event' => $iSetting), "id = '" . App::getUser('id') . "'");	
	$oRespX->addScript("sId('settings_saved').style.display='';setTimeout('sId(\'settings_saved\').style.display=\'none\';', 2000);");
	return $oRespX;
}

function acceptRequest($iId, $iUserId)
{
	$oRespX = new xajaxResponse();
	$oDb =& Database::get();
	$oDb->_delete(App::getT('msg_request'), "requestid = '". $iId ."'");
	// $oDb->update(App::getT('msg_room'), array('type' => '2'), "requestid = '". $iId ."' AND userid = '" . App::getUser('id') . "'");
	$oDb->insert(App::getT('msg_chat'), array('requestid' => $iId, 'text' => '[JOINED]' . App::getUser('user') . '[/JOINED]', 'time' => time()));
	return $oRespX;
}

function deleteRequest($iId)
{
	$oRespX = new xajaxResponse();
	$oDb =& Database::get();
	$oDb->_delete(App::getT('msg_request'), "requestid = '". $iId ."'");
	$oDb->_delete(App::getT('msg_room'), "requestid = '". $iId ."'");
	return $oRespX;
}

function _parseIsJoined($sText)
{
	$sText = stripslashes($sText);
	$sText = trim($sText);
	if (App::getUser('user') == $sText)
	{
		return '';
	}
	return App::format('Mod_Account.user_joined_the_room', $sText);
}

function getMessages($iRequestId, $bReturn = false)
{
	if ( !$bReturn )
	{
		$oRespX = new xajaxResponse();
	}
	chatMembersOnly($oRespX);
	$oDb =& Database::get();

	$aRows = $oDb->getRows("
		SELECT 
			c.text, c.time, u.user, u.msg_event
		FROM ". App::getT('msg_chat') ." AS c
			LEFT JOIN ". App::getT('user') ." AS u ON(c.userid = u.id)
		WHERE c.requestid = '". $iRequestId ."'
		ORDER BY c.time DESC LIMIT 0, 50
	");
	
	if (isset($aRows[0]['user']))
	{
		$aChatSession = md5(serialize($aRows));
		$sChatSessionData = (isset($_SESSION['chat_session'][$aChatSession]) ? $_SESSION['chat_session'][$aChatSession] : '');
		if ($aRows[0]['user'] != App::getUser('user') && $aChatSession != $sChatSessionData)
		{	
			/*
			if (App::getUser('msg_event') == '1') 
			{
				// $oRespX->addScript("window.focus();tinyMCE.getInstanceById('mce_editor_0').getWin().focus();tinyMCE.execCommand('mceSetContent',false, '');");
			}
			*/
			if (!App::getUser('msg_event'))
			{
				$oRespX->addScript("playsound('bg_sound');");				
			}
			
			$_SESSION['chat_session'][$aChatSession] = $aChatSession;
		}
	}

	$aRows = array_reverse($aRows);

	$sData = '';
	foreach( $aRows as $aRow )
	{
		if ( !$aRow['user'] )
		{
			$sSystemText = preg_replace("/\[joined\](.*?)\[\/joined\]/ise", "''._parseIsJoined('$1').''", $aRow['text']);
			$sData .= '<b>' . $sSystemText . '</b>';
		}
		else
		{
			$sData .= '<div style="padding-left:4px; margin-bottom:8px;"> <a style="cursor:pointer;" href="'. App::makeUrl('public.user', array('name' => $aRow['user'])) .'" target="_blank">'. $aRow['user'] .'</a> '. App::format('Mod_Chat.wrote') .':<div style="padding-top:1px; padding-left:8px;">'. $aRow['text'] .'</div></div>';
		}
	}

	if ( $bReturn )
	{
		return $sData;
	}

	$oRespX->addScript(" var bScrollInBottom = document.getElementById('chat_content_div').scrollTop == document.getElementById('chat_content_div').scrollHeight-parseInt(document.getElementById('chat_content_div').style.height);");
	$oRespX->addAssign("chat_content","innerHTML", $sData);	
	$oRespX->addScript('setTimeout("xajax_getMessages(\''. $iRequestId .'\');", 2000);');
	$oRespX->addScript(" if(bScrollInBottom) document.getElementById('chat_content_div').scrollTop = document.getElementById('chat_content_div').scrollHeight;");

	return $oRespX;
}

function checkMessages()
{
	$oRespX = new xajaxResponse();
	chatMembersOnly($oRespX);
	$oDb =& Database::get();

	$oDb->_delete(App::getT('msg_request'), "time < '". (time() - App::getSetting('max_time_online') * 60) ."'");

	$iCnt = $oDb->getField("
		SELECT COUNT(*) FROM
			". App::getT('msg_request') ."
		WHERE ruserid = '". App::getUser('id') ."'
	");

	$oRespX->addScript('setTimeout("xajax_checkMessages()", 4000);');

	if ( !$iCnt )
	{
		$oRespX->addAssign("check_messages","innerHTML", '');
		return $oRespX;
	}

	$oTpl =& App::getTemplate();

	$aRows = $oDb->getRows("
		SELECT m.requestid, u.id, u.user FROM
			". App::getT('msg_request') ." AS m
			JOIN ". App::getT('user') ." AS u ON(m.userid = u.id)
		WHERE m.ruserid = '". App::getUser('id') ."'
		LIMIT 5
	");
	
	if (!App::getUser('msg_event'))
	{
		$sSession = md5(serialize($aRows));
	}

	$oTpl->assign(array
	(
		'aRows' => $aRows,
        'iImChatWidth' => App::getParam('im_chat_width'),
        'iImChatHeight' => App::getParam('im_chat_height')
	));

	$sTemplate = $oTpl->fetch($oTpl->template_dir . '/public/account/messenger/new-messages.html');

	$oRespX->addScript("new Effect.Appear('check_messages');");
	if (!isset($_SESSION['request_session'][$sSession]) && !App::getUser('msg_event'))
	{
		$_SESSION['request_session'][$sSession] = $sSession;
		$oRespX->addScript("playsound('div_sound');");
	}
	if (App::getUser('msg_event') == '1') 
	{
		$oRespX->addScript("window.focus();");
	}
	$oRespX->addAssign("check_messages","innerHTML", $sTemplate);

	return $oRespX;
}

function updateUsersOnline()
{
	$oRespX = new xajaxResponse();
	chatMembersOnly($oRespX);
	$oDb =& Database::get();
	$oDb->update(App::getT('msg_online'), array('time' => time()), "userid = '". App::getUser('id') ."'");
	$oRespX->addScript('setTimeout("xajax_updateUsersOnline();", '. ((App::getSetting('max_time_online') * 60000)) .');');
	return $oRespX;
}

function getUsersOnline($iPage = 0, $bNoRefresh = false)
{
	$oRespX = new xajaxResponse();
	chatMembersOnly($oRespX);
	$oTpl =& App::getTemplate();
	$oDb =& Database::get();
	$oReq =& App::getRequest();
	$oUrl =& App::getUrl();
    App::loadClass('Pager');
	$iPageSize = 15;

	$iTimeout = time() - App::getSetting('max_time_online') * 60;

	$iCnt = $oDb->getField("
		SELECT COUNT(*) FROM
			". App::getT('friends') ." AS f
			JOIN ". App::getT('user') ." AS u ON (f.friend = u.user)
			JOIN ". App::getT('msg_online') ." AS m ON (m.userid = u.id AND m.time > '". $iTimeout ."')
		WHERE f.user = '". App::getUser('user') ."' AND f.top != '2'
	");
	$iOffset = $oDb->_getPageNum($iPage, $iPageSize, $iCnt);

	$sQuery = "
		SELECT f.friend AS user, u.im_status, u.id AS userid, m.time FROM
			". App::getT('friends') ." AS f
			JOIN ". App::getT('user') ." AS u ON (f.friend = u.user)
			JOIN ". App::getT('msg_online') ." AS m ON (m.userid = u.id  AND m.time > '". $iTimeout ."')
		WHERE f.user = '". App::getUser('user') ."' AND f.top != '2'
		ORDER BY f.friend ASC LIMIT ". $iOffset .",". $iPageSize ."
	";
	$aRows = $oDb->getRows($sQuery);

	$oPager = &new Pager($iCnt, $iPage, $iPageSize);
	$iFrom = $oPager->getOffset($iPage, $iPageSize);
	$iTo = (($iFrom + $iPageSize) > $iCnt) ? $iCnt : ($iFrom + $iPageSize);

	$aOptions = App::getOptions('im_status');
	foreach( $aRows as $iKey => $aRow )
	{
		$aRows[$iKey]['profile_info'] = App::format('Mod_Chat.view_users_profile', array($aRow['user']));
		$aRows[$iKey]['imstatus'] = (isset($aOptions[$aRow['im_status']]) ? $aOptions[$aRow['im_status']] : '');
	}

	$oTpl->assign(array
	(
		'aRows' => $aRows,
		'iCnt'             => $iCnt,
        'iFrom'            => ($iCnt) ? ($iFrom + 1) : 0,
		'aPaging'          => ($iCnt) ? $oPager->getInfo($oUrl) : '',
        'iTo'              => $iTo,
        'sRootPath' => $oTpl->template_dir,
        'iImChatWidth' => App::getParam('im_chat_width'),
        'iImChatHeight' => App::getParam('im_chat_height')
	));

	$sTemplate = $oTpl->fetch($oTpl->template_dir . '/public/account/messenger/online.html');

	$oRespX->addAssign("whos_online","innerHTML", $sTemplate);
	if ( !$bNoRefresh )
	{
		$oRespX->addScript('setTimeout("xajax_getUsersOnline(document.getElementById(\'page_num\').value)", 6000);');
	}

	return $oRespX;
}

function chatMembersOnly(&$oRespX)
{
	if ( !App::getUser('user') )
	{
		$oRespX->addScript("window.close();");
		return $oRespX;
	}
}

?>